// Package alertconverter provides functions to convert alerts from different sources
// to the unified AlertData format used by the system.
package alertconverter

import (
	"fmt"
	"strings"
	"time"
	"v2/model"
)

// KubeEventAlert represents the alert format from Kubernetes events
type KubeEventAlert struct {
	Type           string `json:"type"`
	Reason         string `json:"reason"`
	Message        string `json:"message"`
	FirstTimestamp string `json:"firstTimestamp"`
	LastTimestamp  string `json:"lastTimestamp"`
	Count          int    `json:"count"`
	Kind           string `json:"kind"`
	Name           string `json:"name"`
	Namespace      string `json:"namespace"`
}

// KubeeventerFlatEvent represents the flat event format from kubeeventer
type KubeeventerFlatEvent struct {
	EventType      string `json:"EventType"`
	EventKind      string `json:"EventKind"`
	EventReason    string `json:"EventReason"`
	EventTime      string `json:"EventTime"`
	EventMessage   string `json:"EventMessage"`
	EventObject    string `json:"EventObject"`
	EventNamespace string `json:"EventNamespace"`
	// 添加标签字段用于存储URL参数中的标签
	Labels []string `json:"-"` // 添加 omitempty 标签
}

// ConvertKubeEventAlert converts a Kubernetes event to the unified AlertData format
func ConvertKubeEventAlert(kubeEvent KubeEventAlert) model.AlertData {
	severity := 4 // 默认为信息级别
	if kubeEvent.Type == "Warning" {
		severity = 3 // 警告
	} else if kubeEvent.Type == "Error" {
		severity = 2 // 重要
	} else if kubeEvent.Type == "Critical" {
		severity = 1 // 紧急
	}

	// 解析时间戳
	triggerTime := time.Now().Unix()
	if parsedTime, err := time.Parse(time.RFC3339, kubeEvent.FirstTimestamp); err == nil {
		triggerTime = parsedTime.Unix()
	}

	// 构建标签
	tagsMap := map[string]string{
		"kind":      kubeEvent.Kind,
		"name":      kubeEvent.Name,
		"namespace": kubeEvent.Namespace,
		"reason":    kubeEvent.Reason,
		"type":      kubeEvent.Type,
		"message":   kubeEvent.Message,
	}

	tags := make([]string, 0, len(tagsMap))
	for k, v := range tagsMap {
		tags = append(tags, k+"="+v)
	}

	return model.AlertData{
		ID:            hashStringToInt(kubeEvent.Name + kubeEvent.Namespace + kubeEvent.Reason),
		Cate:          "kube-event",
		RuleName:      kubeEvent.Reason,
		RuleNote:      kubeEvent.Message,
		TriggerTime:   triggerTime,
		Severity:      severity,
		Tags:          tags,
		TagsMap:       tagsMap,
		FormattedTime: time.Unix(triggerTime, 0).Format("2006-01-02 15:04:05"),
	}
}

// ConvertKubeeventerFlatEvent converts a kubeeventer flat event to the unified AlertData format
func ConvertKubeeventerFlatEvent(kubeeventerEvent KubeeventerFlatEvent) model.AlertData {
	severity := 4 // 默认为信息级别
	if kubeeventerEvent.EventType == "Warning" {
		severity = 3 // 警告
	} else if kubeeventerEvent.EventType == "Error" {
		severity = 2 // 重要
	} else if kubeeventerEvent.EventType == "Critical" {
		severity = 1 // 紧急
	}

	// 解析时间戳
	triggerTime := time.Now().Unix()
	if parsedTime, err := time.Parse("2006-01-02 15:04:05 -0700 MST", kubeeventerEvent.EventTime); err == nil {
		triggerTime = parsedTime.Unix()
	}

	// 构建标签
	tagsMap := map[string]string{
		"kind":      kubeeventerEvent.EventKind,
		"reason":    kubeeventerEvent.EventReason,
		"type":      kubeeventerEvent.EventType,
		"message":   kubeeventerEvent.EventMessage,
		"object":    kubeeventerEvent.EventObject,
		"namespace": kubeeventerEvent.EventNamespace,
	}

	// 添加URL参数中的标签
	for _, label := range kubeeventerEvent.Labels {
		// 清理标签格式，移除方括号
		cleanLabel := strings.Trim(label, "[]")
		tagsMap["label"] = cleanLabel
		// 也添加到标签列表中
		tagsMap["labels"] = strings.Join(kubeeventerEvent.Labels, ",")
	}

	tags := make([]string, 0, len(tagsMap))
	for k, v := range tagsMap {
		tags = append(tags, k+"="+v)
	}

	// 生成事件名称
	eventName := kubeeventerEvent.EventReason
	if kubeeventerEvent.EventKind != "" {
		eventName = kubeeventerEvent.EventKind + "-" + eventName
	}

	// 使用EventObject作为RuleName，如果存在的话
	ruleName := kubeeventerEvent.EventReason
	if kubeeventerEvent.EventObject != "" {
		ruleName = kubeeventerEvent.EventObject
	}

	return model.AlertData{
		ID:            hashStringToInt(eventName + kubeeventerEvent.EventTime),
		Cate:          "kube-event",
		RuleName:      ruleName,
		RuleNote:      kubeeventerEvent.EventMessage,
		TriggerTime:   triggerTime,
		Severity:      severity,
		Tags:          tags,
		TagsMap:       tagsMap,
		FormattedTime: time.Unix(triggerTime, 0).Format("2006-01-02 15:04:05"),
	}
}

// GenerateKubeEventCardMessage 生成Kubernetes事件的卡片消息，适用于所有IM渠道
func GenerateKubeEventCardMessage(alertData model.AlertData) string {
	// 构建易于阅读的文本格式消息
	message := fmt.Sprintf(
		"Kubernetes事件告警\n\n"+
			"事件类型: %s\n"+
			"事件对象: %s\n"+
			"命名空间: %s\n"+
			"事件原因: %s\n"+
			"事件种类: %s\n"+
			"触发时间: %s\n"+
			"严重级别: %s\n"+
			"事件消息: %s\n"+
			"告警ID: %d",
		getStringFromMap(alertData.TagsMap, "type", "Unknown"),
		getStringFromMap(alertData.TagsMap, "object", getStringFromMap(alertData.TagsMap, "name", "Unknown")),
		getStringFromMap(alertData.TagsMap, "namespace", "default"),
		getStringFromMap(alertData.TagsMap, "reason", "Unknown"),
		getStringFromMap(alertData.TagsMap, "kind", "Unknown"),
		alertData.FormattedTime,
		getSeverityText(alertData.Severity),
		getStringFromMap(alertData.TagsMap, "message", "Unknown"),
		alertData.ID,
	)

	return message
}